package com.leo.javase.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * IO工具类
 * @author Lian
 *
 */
public class IOUtils {
	/**
	 * 一个一个字节的读取文件，并用16进制打印
	 * @param filename
	 * @throws Exception
	 */
	public static void printHex(String filename)throws Exception{
		FileInputStream in = new FileInputStream(filename);
		int b = 0, j = 0;
		while((b = in.read())!=-1){
			if(b < 0xf)
				System.out.print("0");
			System.out.print(Integer.toHexString(b) + " ");
			if((j++)%10==0)
				System.out.println();
		}
		System.out.println();
		in.close();
	}
	/**
	 * 读取1KB数据到字节数组中
	 * @param filename
	 * @throws Exception
	 */
	public static void printHexByByteArray(String filename)throws Exception{
		FileInputStream in = new FileInputStream(filename);
		byte[] buf = new byte[1024];
		int bytes = 0, j = 1;
		while((bytes = in.read(buf, 0, buf.length))!=-1){
			for(int i=0; i<bytes; i++){
				System.out.print(Integer.toHexString(buf[i] & 0xff) + " ");
				if((j++)%10==0)
					System.out.println();
			}
		}
		System.out.println();
		in.close();
	}
	/**
	 * 字节流实现文件的复制
	 * 一次读取8KB的数据，批量字节读取文件
	 * @param srcFile
	 * @param destFile
	 */
	public static void copyFileByStream(File srcFile,File destFile)throws Exception{
		if(!srcFile.exists())
			throw new IllegalArgumentException("文件不存在！");
		if(!srcFile.isFile())
			throw new IllegalArgumentException("不是文件！");
		FileInputStream in = new FileInputStream(srcFile);
		FileOutputStream out = new FileOutputStream(destFile);
		byte[] buf = new byte[8 * 1024];
		int b = 0;
		while((b = in.read(buf, 0, buf.length))!=-1){
			out.write(buf, 0, b);
			out.flush();
		}
		in.close();
		out.close();
		
	}
	/**
	 * 批量、缓冲复制文件
	 * @param srcFile
	 * @param destFile
	 */
	public static void copyFileByBuffered(File srcFile,File destFile)throws Exception{
		if(!srcFile.exists())
			throw new IllegalArgumentException("文件不存在！");
		if(!srcFile.isFile())
			throw new IllegalArgumentException("不是文件！");
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(srcFile));
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile));
		byte[] buf = new byte[20 * 1024];
		int b = 0;
		while((b = in.read(buf, 0, buf.length))!=-1){
			out.write(buf, 0, b);
			out.flush();
		}
		in.close();
		out.close();
	}
	
}
